//
//  WXLogin.swift
//  ExtremeHealth
//
//  Created by Zhongkai Li 李忠凯 on 2018/9/25.
//  Copyright © 2018 GanDongKeJi. All rights reserved.
//

import RxSwift

class WXLogin: NSObject, WXApiDelegate {
    private let wxSchemes: String = "wxb6e484cf616e39fb"
    private let bag = DisposeBag()

    override init() {
        WXApi.registerApp(wxSchemes)
    }

    func canHandle(_ urlSchemes: String?) -> Bool {
        return urlSchemes == wxSchemes
    }

    func handleOpen(_ url: URL) -> Bool {
        return WXApi.handleOpen(url, delegate: self)
    }

    func onReq(_ req: BaseReq!) {
        debugPrint(req.type)
    }

    func onResp(_ resp: BaseResp!) {
        guard let authResp = resp as? SendAuthResp else { debugPrint("resp is not send auth resp"); return }
        debugPrint("ErrCode : \(authResp.errCode)") // 0
        debugPrint("EodeStr : \(String(describing: authResp.errStr))") // nil
        debugPrint("Code : \(String(describing: authResp.code))") // 0017Avci0BJ0Rj1hIqai0jEsci07AvcI
        debugPrint("State : \(String(describing: authResp.state))") //  State : App
        debugPrint("Lang : \(String(describing: authResp.lang))") // nil
        debugPrint("Country : \(String(describing: authResp.country))") // nil
        guard authResp.errCode == 0,
            let code = authResp.code else { debugPrint("error in send auth resp"); return }
        WXLoginViewModel()
            .login(code: code, disposeBag: bag)
    }
}
